<?php
//----------------------------------------------------------------------------------------------------------------------------
    include_once($config['app_dir'] . '/includes/object.class.php');
    include_once($config['app_dir'] . '/includes/FormParams.class.php');
    include_once($config['app_dir'] . '/includes/params.class.php');
    include_once($config['app_dir'] . '/includes/db.class.php');
    //------------------------------------------------------------------------------------------------------------------------
    class objTranslationLanguage  extends objObject {
            protected $_db = false;
            protected $_sql_querys = false;

        public function __construct() {
            $this->_db = objDataBase::GetInstance();
            $this->_sqls();
        } //constructor

        public function ClassName() {
            return  __CLASS__;
        }//ClassName

        public function getLanguage($aLang=false) {
            if( $aLang ) $result = $this->_db->handler->GetAll($this->_sql_querys['language'], $this->_lang);
                else $result = $this->_db->handler->GetAll($this->_sql_querys['language'], $this->_lang);
            return $result;
        }//getLanguage

        protected function _sqls() {
            $this->_sql_querys['list_param'] =
            " SELECT tl.id ".
            " FROM fa_language tl ".
            " WHERE tl.sys_name='?' ";
            //---------------------------------------------------------------------------------------------------------------
            $this->_sql_querys['list'] =
            " SELECT tl.id ".
            " FROM fa_language tl ".
            " WHERE tl.sys_name='?' ";
        } //_sqls

    }//class TranslationLanguage
    //------------------------------------------------------------------------------------------------------------------------
    class objTranslationMessage extends objObject {
            public $cache_time = 0;

            protected $_db = false;
            protected $_sql_querys = false;

            protected $_lang = 'en';
            protected $_default_lang = 'en';

            private static $instance;

        private function __construct() {
          global $config;
            $this->_db = objDataBase::GetInstance();
            $this->_sqls();

            $this->cache_time = $config['translation']['cache_lifetime'];
        } //constructor

        public static function GetInstance() {
            if( !isset(self::$instance) ) {
                $c = __CLASS__;
                self::$instance = new $c;
            }
            return self::$instance;
        } //GetInstance

        public function __clone()    {
            throw new Exception('Cant clone singleton');
        } //clone

        public function ClassName() {
            return  __CLASS__;
        }//ClassName

        public function SetLang($aLang) {
            if( $aLang ) $this->_lang = strtolower($aLang);
        }//SetLang

        public function GetLang() {
            return $this->_lang;
        }//GetLang

        public function SetDefaultLang($aLang) {
            if( $aLang ) $this->_default_lang = strtolower($aLang);
        }//SetDefaultLang

        public function getData($aConst=false) {
            if( false===($lang_id = $this->getLanguageID()) ) return false;

            $query = $this->_sql_querys['messages'];
            $query .= " WHERE lang.id = $lang_id ";
            if( $aConst ) $query .= " AND concat(const.resource,'__',const.name)= '$aConst' ";

            return $this->_db->handler->CacheGetAll($this->cache_time, $query);
        }//getData

        public function getMessage($aConst=false) {
            $data = $this->getData($aConst);
            return $data[0]['label_text'];
        }//getMessage

        public function getLanguageID() {
            return $this->_db->handler->GetOne($this->_sql_querys['language'], $this->_lang);
        }//getLanguageID

        protected function _sqls() {
            $this->_sql_querys['messages'] =
            " SELECT ".
                " lang.name AS lang_name, ".
                " lang.sys_name AS lang_sys_name, ".
                " lang.id AS lang_id, ".
                " const.id AS const_id, ".
                " const.resource , ".
                " concat(const.resource,'__',const.name) AS const_name, ".
                " lab.id AS label_id, ".
                " lab_en.`text` as label_en, ".
                " COALESCE(lab.`text`, lab_en.`text`) as label_text ".
            " FROM fa_language lang ".
                " CROSS JOIN fa_const const ".
                " LEFT OUTER JOIN fa_label lab ON (lang.id = lab.language_id AND lab.const_id = const.id) ".
                " LEFT OUTER JOIN fa_label lab_en ON (lab_en.const_id = const.id AND ".
                                                    " lab_en.language_id IN ( ".
                                                        " SELECT distinct tl.id ".
                                                        " FROM fa_language tl ".
                                                        " WHERE tl.sys_name='$this->_default_lang' ".
                                                        " ) ".
                                                    " ) ";
            //--------------------------------------------------------------------------------------------------------
            $this->_sql_querys['language'] =
            " SELECT distinct tl.id ".
            " FROM fa_language tl ".
            " WHERE tl.sys_name=? ";
        }//_sqls

    } //class TranslationMessage
    //-----------------------------------------------------------------------------------------------------------------
    class objTranslationConf extends  objTranslationMessage {
            public $path = false;
            public $cache_time = 0;//in seconds

            private static $instance;

        private function __construct() {
          global $config;
            $this->_db = objDataBase::GetInstance();
            $this->_sqls();

            $this->cache_time = $config['translation']['cache_lifetime'];
            $this->path = $config['smarty']['config_dir'];
        } //constructor

        public static function GetInstance() {
            if( !isset(self::$instance) ) {
                $c = __CLASS__;
                self::$instance = new $c;
            }
            return self::$instance;
        } //GetInstance

        public function ClassName() {
            return  __CLASS__;
        }//ClassName

        public function Render($prefix=false) {
            $result = '';
            if( $prefix && $this->isEmpty($prefix) ) return $result;

            $lang_rs = $this->_db->handler->Execute($this->_sql_querys['language']);

            $lang_rs->MoveFirst();
            while( !$lang_rs->EOF ) {
                //---------------------------------------------------------------------------------------------------
                $query = $this->_sql_querys['messages'];
                if( !$prefix )  $label_rs = $this->_db->handler->Execute($this->_sql_querys['messages'], array($lang_rs->fields['sys_name']));
                    else $label_rs = $this->_db->handler->Execute($this->_sql_querys['messages_resource'], array($lang_rs->fields['sys_name'], $prefix));

                $first_label = true;
                $label_rs->MoveFirst();
                while( !$label_rs->EOF ) {
                    if( $first_label ) {
                        $result .= "\n[". $lang_rs->fields['sys_name'] . "]\n";
                        $first_label = false;
                    }//first time
                    $result .= $label_rs->fields['const_name'] . '=';
                    $bflag = (false !== strpos($label_rs->fields['label_text'], "\n"));
                    $result .= ($bflag ? '"""' : '"' ) . $label_rs->fields['label_text'] . ($bflag ? '"""' : '"' ) . "\n";

                    $label_rs->MoveNext();
                } //while - labels
                $label_rs->Close();
                //---------------------------------------------------------------------------------------------------

                $lang_rs->MoveNext();
            } //while - language
            $lang_rs->Close();

            return $result;
        }//Render

        protected function isEmpty($prefix){
            return 0===intval($this->_db->handler->GetOne($this->_sql_querys['check'], array($prefix)));
        } //isEmpty

        protected function GetFilename($prefix) {
            if( $prefix ) return $this->path . $prefix . '.conf';
                else return false;
        }//GetFilename

        public function RenderFile($prefix=false) {
            if( !($filename = $this->GetFilename($prefix)) ) return false;

            if( $this->isCached($prefix) ) return $filename;

            if( $content = $this->Render($prefix) ) {
                $handle = fopen($filename, 'w');
                fwrite($handle, $content);
                fclose($handle);
            } //content is not empty

            return $filename;
        }//RenderFile

        public function RenderAllFiles() {
            $resource_rs = $this->_db->handler->Execute($this->_sql_querys['resource']);

            $resource_rs->MoveFirst();
            while( !$resource_rs->EOF ) {
                /*var_dump*/($this->RenderFile($resource_rs->fields['resource']));

                $resource_rs->MoveNext();
            } //while - resource
            $resource_rs->Close();

        }//RenderAllFiles

        public function isCached($prefix=false) {
            $result = false;
            $filename = $this->GetFilename($prefix);

            if( file_exists($filename) ) {
                if( -1===intval($this->cache_time) ) $result= true;
                elseif( 0===intval($this->cache_time) )  $result= false;
                    else $result =  ( ( time() - filemtime($filename) ) < intval($this->cache_time) );
                if( !$result ) @unlink($filename);
            }//if file exists

            return $result;
        }//isCached

        public function Display($prefix=false) {
            echo $this->Render($prefix);
        } //Display

        protected function _sqls() {
            parent::_sqls();
            $this->_sql_querys['messages'] .= ' WHERE lang.sys_name=? ';
            $this->_sql_querys['messages_resource'] = $this->_sql_querys['messages'] . ' AND resource=? ';
            $this->_sql_querys['language'] = 'SELECT * FROM fa_language ';
            $this->_sql_querys['resource'] = 'SELECT DISTINCT resource FROM  fa_const ';
            $this->_sql_querys['check'] =
                " SELECT count(*) AS count_labels ".
                " FROM ".
                    " fa_language lang ".
                    " RIGHT OUTER JOIN fa_label label ON (lang.id = label.language_id) ".
                    " LEFT OUTER JOIN fa_const const ON (label.const_id = const.id) ".
                " WHERE resource=? ";
        }//_sqls

    }//class TranslationConf
    //-----------------------------------------------------------------------------------------------------------------------
    class objTranslationLangSelector{
                protected $data = false;
                protected $DataBase = false;
                public $TranslationMessage = false;

            public function __construct($default_language='en') {
              global $Staff;
                $this->DataBase = objDataBase::GetInstance();

                if( !$Staff->Session->isExists('lang') && $Staff->Login() ) $Staff->Session->Put('lang', $Staff->UserLanguage());

                $ParamsLangSelect = new objFormParams('post', 'selectlang_');
                if( $params_lang = $ParamsLangSelect->getAssocArray() ) {
                    $lang_id = $params_lang['lang'];
                    $Staff->Session->Put('lang', $lang_id);
                }
                elseif( array_key_exists('lang', $_REQUEST) && !empty($_REQUEST['lang']) ) {
                	$lang_id = $_REQUEST['lang'];
                	$Staff->Session->Put('lang', $lang_id);
                }

                elseif( $Staff->Session->isExists('lang') ) $lang_id = $Staff->Session->Get('lang');


                if( !$lang_id ) {
                    $lang_id = $default_language;
                    $Staff->Session->Put('lang', $lang_id);
                }

                $TranslationMessage = objTranslationMessage::GetInstance();
            	$TranslationMessage->SetLang($this->GetLang());
				$this->TranslationMessage = $TranslationMessage;

                $ParamsLang = new objParamList('lang');
                $ParamsLang->Build($this->DataBase->handler, "SELECT sys_name as value, `name` FROM fa_language");


                $this->data['list'] = $ParamsLang->getAssocArray();

                $this->data['value'] = $lang_id;
                $this->data['name'] = "selectlang_lang";
                $this->data['caption'] = $this->TranslationMessage->GetMessage('menu_langselector__msgLangCaption');
            } //constructor

            public function GetLang() {
              global $Staff;
                return $Staff->Session->Get('lang');
            }//GetLang


            public function Render($template='menus/menu_langselector.tpl') {
                $SelectForm = new objTemplate();
                $SelectForm->Assign('select', $this->data);
                return $SelectForm->Fetch($template);
            }//Render
    }// class class TranslationLangSelector
    //----------------------------------------------------------------------------------------------------------------------
    class objSystemSelector {
            protected $system_id = false;
            protected $default_system = false;
            protected $lang = false;
            protected $data = false;
            protected $DataBase = false;
            protected $flag_all = true;
            protected $template_filename = 'snippet/form_systemselect.tpl';
            protected $flag_prepared = false;

            public $action_script = " document.getElementById('form_system_select').submit();";
            public $before_action_script = "";
            public $after_action_script = "";

        public function __construct($default_system=false, $flag_all=false, $flag_prepare=true) {
          global $Staff;
            $this->default_system = $default_system;
            $this->flag_all = $flag_all;
            $this->lang = $Staff->Session->Get('lang');

            $this->DataBase = objDataBase::GetInstance();

            if( $flag_prepare ) {
                $this->ChangeSystem();
                $this->Prepare($this->system_id, $this->lang);
            }
        } //constructor

        protected function ChangeSystem() {
            $system_id = false;

            if( array_key_exists('selectsystem_system', $_POST) ) {
                $system_id = $_POST['selectsystem_system'];
            }
            elseif( array_key_exists('system', $_REQUEST)  ) {
                $system_id = $_REQUEST['system'];
            }

            $this->SetSystem($system_id);
        } //ChangeSystem

        public function SetSystem($system_id) {
          global $Staff;
            $this->system_id = $system_id;
            if( false===$this->system_id )
                $this->system_id = $this->default_system;
            $Staff->Session->Put('system', intval($this->system_id));

            $this->flag_prepared = false;
        } //SetSystem

        public function GetSystem() {
         global $Staff;
            return $Staff->Session->Get('system');
        }//GetSystem

        protected function Prepare($system_id, $lang_id) {
            $this->flag_prepared = false;
            $ParamsSystem = new objParamList('system');

            if( $this->flag_all )
                $ParamsSystem->Add(new objParamItem('All Systems', '0'));

            $ParamsSystem->Build($this->DataBase->handler,
                                 "SELECT SystemID as value, `Name` as name FROM fa_systems WHERE Active=1 ORDER BY SystemOrder ASC",
                                 'value', 'name', 'flag', false, false);

            $TranslationMessage = objTranslationMessage::GetInstance();
            $TranslationMessage->SetLang($lang_id);

            $this->data['list'] = $ParamsSystem->getAssocArray();
            $this->data['value'] = intval($system_id);
            $this->data['name'] = "selectsystem_system";
            $this->data['mapcaption'] = $TranslationMessage->GetMessage('menu_systemselector__msgMapCaption');
            $this->data['caption'] = $TranslationMessage->GetMessage('menu_systemselector__msgSystemCaption');
            $this->flag_prepared = true;

            return $this->flag_prepared;
        } //Prepare

        public function Render($template=false) {
            if( !$this->flag_prepared ) {
                $this->ChangeSystem();
                $this->Prepare($this->system_id, $this->lang);
            }//if not prepared yet

            $SelectForm = new objTemplate();

            $SelectForm->Assign('select', $this->data);
            $SelectForm->Assign('BeforeActionScript',$this->before_action_script);
            $SelectForm->Assign('ActionScript', $this->action_script);
            $SelectForm->Assign('AfterActionScript', $this->after_action_script);

            return $SelectForm->Fetch( ($template ? $template : $this->template_filename) );
        }//Render

    }//class SystemSelector

//---------------------------------------------------------------------------------------------------------------------------

class objMAPSelector {
            protected $data = false;
            protected $DataBase = false;
            protected $form2Submit;

        public function __construct($default_system=false) {

          global $Staff;
            $this->form2Submit = $form2Submit;
            $this->DataBase = objDataBase::GetInstance();



            //if( !$Staff->Session->isExists('system') && $Staff->Login() ) $Staff->Session->Put('system', $Staff->SystemID());//XXX change staff class

            $ParamsSystemSelect = new objFormParams('post', 'selectsystem_');
            if( $params_system = $ParamsSystemSelect->getAssocArray() ) {
            	$selectParams = explode('_',$params_system['system']);
            	$program_id = $selectParams[0];
                $system_id = $selectParams[1];
                $program_lot = $selectParams[2];
                $program_deposit = $selectParams[3];
                $program_leverage = $selectParams[4];
                $Staff->Session->Put('system', $system_id);
            }
            //elseif( array_key_exists('system', $_REQUEST) && !empty($_REQUEST['system']) ) {
                //$system_id = $_REQUEST['system'];
                //$Staff->Session->Put('system', $system_id);
            //}
            else {
            	if( $Staff->Session->isExists('system') ) {
            		$system_id = $Staff->Session->Get('system');

            		$query = "SELECT count(*) as Programs, ".
		            	"(SELECT p.ID FROM fa_map p WHERE p.Active=1 ORDER BY p.ID LIMIT 0,1) as DefaultProgram, ".
		            	"(SELECT s.SystemID FROM fa_map s WHERE s.Active=1 ORDER BY s.ID LIMIT 0,1) as DefaultSystem".
		            	" FROM fa_map WHERE SystemID=? and Active=1";
		       		$query2 = "SELECT SystemID, ID, CalcLot, CalcDeposit, CalcLeverage ".
            			" FROM fa_map WHERE SystemID=? and Active=1 ORDER BY ID DESC";

            		$rsp = $this->DataBase->handler->getRow($query, array($system_id));






            		if ($rsp['Programs']==0) {
            			$rspData = $this->DataBase->handler->getRow($query2, array($rsp['DefaultSystem']));
		            	$system_id = $rspData['SystemID'];
		            	$Staff->Session->Put('system', $system_id);
	            	} else {
	          			$rspData = $this->DataBase->handler->getRow($query2, array($system_id));
	          		}

	          		$program_id = $rspData['ID'];
		            $program_lot = $rspData['CalcLot'];
		            $program_deposit = $rspData['CalcDeposit'];
		            $program_leverage = $rspData['CalcLeverage'];






                }



            }

            //if( !$system_id ) {
                //$system_id = $default_system;
                //$Staff->Session->Put('system', $system_id);
            //}

            //$ParamsSystem = new objParamList('system');

            //$xxx = $this->DataBase->handler->getAssoc("SELECT SystemID as value, `Name` as name FROM fa_systems WHERE Active=1");

            $TranslationConf = objTranslationConf::GetInstance();
		    $TranslationConf->RenderFile('_map_list');

            $TranslationMessage = objTranslationMessage::GetInstance();
            $TranslationMessage->SetLang($Staff->Session->Get('lang'));

            // check is there any MAP for selected system and if it's absent than use default system for program

            $rsp = $this->DataBase->handler->getRow("SELECT count(*) as Programs, ".
                "(SELECT d.SystemID FROM fa_map d WHERE d.Active=1 ORDER BY d.ID LIMIT 0,1) as DefaultSystem, ".
                "(SELECT d.ID FROM fa_map d WHERE d.Active=1 ORDER BY d.ID LIMIT 0,1) as DefaultProgram".
                " FROM fa_map WHERE SystemID=".$system_id." and Active=1");
            if ($rsp['Programs']==0) {
                $system_id = $rsp['DefaultSystem'];
                $Staff->Session->Put('system', $system_id);
            }



            //$rsp = $this->DataBase->handler->getRow($query,array($system_id));




            //$this->data['list'] = $ParamsSystem->getAssocArray();
            $this->data['list'] = $this->DataBase->handler->getAll("SELECT * FROM fa_map WHERE Active=1");



            //var_dump($this->data['list']);

            $this->data['value'] = $program_id."_".$system_id."_".$program_lot."_".$program_deposit."_".$program_leverage;
			$this->data['current']['mapid'] = $program_id;
            $this->data['current']['lot'] = $program_lot;
            $this->data['current']['deposit'] = $program_deposit;
            $this->data['current']['leverage'] = $program_leverage;
            $this->data['name'] = "selectsystem_system";
            $this->data['mapcaption'] = $TranslationMessage->GetMessage('menu_mapselector__msgMapCaption');
            $this->data['mapsuffix'] = $TranslationMessage->GetMessage('menu_mapselector__labelProgram');
        } //constructor

        public function GetSystem() {
         global $Staff;
            return $Staff->Session->Get('system');
        }//GetSystem

		public function GetMAPID() {
            return $this->data['current']['mapid'];
        }//GetSystem

        public function Render($template='snippet/form_mapselect.tpl'){
            $SelectForm = new objTemplate();
            $SelectForm->Assign('select', $this->data);
            return $SelectForm->Fetch($template);
        }//Render

    }//class objMAPSelector

?>
